package westh.ilib.service;

import java.util.Map;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.ArrayList;

import net.sf.json.JSONObject;
import net.sf.json.JSONArray;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.mule.extras.client.MuleClient;
import org.mule.impl.MuleMessage;
import org.mule.umo.UMOMessage;
import westh.config.Config;

/**
 * @author gaoyang
  * modified:zhangjian 
 * date    :2010-09-15
 * content :add method get clouds Ip address
 */

public class HotResourceService {
	private final static Log log = LogFactory.getLog(HotResourceService.class);
	//get clouds Ip address
	String localhostUrl = Config.get("localhostUrl");
	String remoteUrl = Config.get("remoteUrl");
	/*
	 * from ULAS
	 * according to start time and end time
	 * get resource id list
	 * sorted by inverted order of clicks
	 * 从ULAS中，根据查询起止时间，按照资源点击次数倒序，得到资源id列表。
	 */
	public String getHotResIdListByDate (String dateStart, String dateEnd) {
		JSONObject inStr = new JSONObject();       // package the parameters got from front stage
		String start = dateStart + " 00:00:00";    // start date and time
		String end = dateEnd + " 23:59:59";        // end date and time
		inStr.put("qDateStart", start);
		inStr.put("qDateEnd", end);
		
		JSONObject inJson = new JSONObject();      // package the data to send to back stage
		String methodName = "getHotRscIdList";     // method name in back stage called by mule
		inJson.put("methodName", methodName);
		inJson.put("jsonStr", inStr);
		String inputStr = inJson.toString();       // convert the inJson into string to send
		log.debug("inputStr of getHotResIdListByDate :");
		log.debug(inputStr);
		
		/* get jSon information start */
		String outString = "";                     // get resource id list result output by mule
		try {
			log.debug("aaaaaaaaaaaaaaaaaaaaaaaaaaaa"+outString);
			MuleClient client = new MuleClient();
			//call WebService
			UMOMessage umo = client.send("axis:http://"+remoteUrl+":9281/Service/ulasService?method=rulesControl", inputStr, null);
			outString = (String)umo.getPayload();
			log.debug("aaaaaaaaaaaaaaaaaaaaaaaaaaaa"+outString);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		/* get jSon information end */
		
//		/* parse jSon information start */
//		JSONObject jsonOut = JSONObject.fromObject(outString);
//		String retCode = jsonOut.getString("retCode");      // return code
//		String retMsg = jsonOut.getString("retMsg");        // return result message
//		String resIdList = "";                              // return resource id list
//		log.debug("retCode = " + retCode);
//		log.debug("retMsg = " + retMsg);
//		if (retCode.equals("3501")) {
//			//String result = jsonOut.getString("rscIdList");
//			//JSONArray resultArray = JSONArray.fromObject(result);
//			JSONArray resultArray = jsonOut.getJSONArray("resultArray");
//			log.debug(resultArray.toString());
//			for (int i = 0; i < resultArray.size(); i++) {
//				JSONObject temp = JSONObject.fromObject(resultArray.get(i));
//				String rscId = temp.getString("rscId");
//				int visitCount = temp.getInt("visitCount");
//				log.debug("rscId = " + rscId);
//				log.debug("visitCount = " + visitCount);
//			}
//		} else {
//		}
//		/* parse jSon information end */
		
		log.debug("function getHotResIdListByDate() return");
		
		return outString;
	}
	
	/*
	 * from iDLib
	 * according resource id list and the number of resources input by user
	 * choose the appropriate resource id list
	 * 从iDLib中，资源id列表和用户输入的资源显示条数，筛选出符合需求的资源id列表。 
	 */
	public String refineHotResIdListByCount (String resIdList, String resCount) {
		JSONObject resIdListJSON = JSONObject.fromObject(resIdList);
		String retCode = resIdListJSON.getString("retCode");
		String refineIdList = "";    // id list refined by resource count
		
		/* hot resource id list is not empty if return code equals 3501 */
		if (retCode.equals("3501")) {
			String retMsg = resIdListJSON.getString("retMsg");
			JSONArray rscIdListJSONArray = resIdListJSON.getJSONArray("resultArray");
			int n = rscIdListJSONArray.size();
			int m = Integer.parseInt(resCount) - 1;
			for (int i = n-1; i > m; i--) {
				rscIdListJSONArray.remove(i);
			}
			JSONObject refineIdListJSON = new JSONObject();    // refine id list in json by resource count
			refineIdListJSON.put("retCode", retCode);
			refineIdListJSON.put("retMsg", retMsg);
			refineIdListJSON.put("resultArray", rscIdListJSONArray);
			refineIdList = refineIdListJSON.toString();
		} else {    // hot resource id list is empty or service error
			return resIdList;
		}
		
		log.debug("function refineHotResIdListByCount() return");
		
		return refineIdList;
	}
	
	/*
	 * from CDO
	 * according to resource id list
	 * get resource details list
	 * 从CDO中，根据资源id列表，得到资源元数据列表。
	 */
	public String getHotResByIdList (String resIdList) {
		JSONObject resIdListJSON = JSONObject.fromObject(resIdList);
		String retCode = resIdListJSON.getString("retCode");
		String retMsg = resIdListJSON.getString("retMsg");
		String resList = "";    // resource information list
		
		/* hot resource id list is not empty if return code equals 3501 */
		if (retCode.equals("3501")) {
			JSONArray rscIdListJSONArray = resIdListJSON.getJSONArray("resultArray");
			int n = rscIdListJSONArray.size();
			//log.debug(rscIdListJSONArray);
			//log.debug(n);
			JSONArray rscListJSONArray = new JSONArray();    // resource information array in json
			for (int i = 0; i < n; i++) {
				JSONObject tempJSON = JSONObject.fromObject(rscIdListJSONArray.get(i));
				String rscId = tempJSON.getString("rscId");
				int visitCount = tempJSON.getInt("visitCount");
				
				JSONObject inStr = new JSONObject();      // package the parameters got from front stage
				inStr.put("rscId", rscId);
				
				
				JSONObject inJson = new JSONObject();     // package the data to send to back stage
				String methodName = "getRscInfoById";     // method name in back stage called by mule
				inJson.put("methodName", methodName);
				inJson.put("jsonStr", inStr);
				String inputStr = inJson.toString();
				
				log.debug(inStr);
				
				/* get jSon information start */
				String outString = "";                    // get resource information result output by mule
				try {
					log.debug("aaaaaaaaaaaaaaaaaaaaaaaaaaaa"+outString);
					MuleClient client = new MuleClient();
					//call WebService
					//UMOMessage umo = client.send("axis:http://localhost:4381/LIBJson/iDlibJson?method=rulesControl", inputStr, null);
					UMOMessage umo = client.send("axis:http://"+localhostUrl+":4381/LIBJson/iDlibJson?method=getRscInfoById", inStr.toString(), null);
					outString = (String)umo.getPayload();
					log.debug("aaaaaaaaaaaaaaaaaaaaaaaaaaaa"+outString);
				} catch (Exception e) {
					throw new RuntimeException(e);
				}
				/* get jSon information end */
				
				log.debug(outString);
				
				JSONObject jsonOut = JSONObject.fromObject(outString);
				int code = jsonOut.getInt("retCode");
				
				/* resource information is not empty if return code equals 0 */
				if (code == 0) {
					/* package this resource information */
					log.debug(code);
					JSONObject resultJSON = jsonOut.getJSONObject("result");
					if(resultJSON==null)
						continue;
					String rscTitle = resultJSON.getString("rscTitle");
					if(rscTitle==null)
					{
						rscTitle="";
					}
					String rscType = resultJSON.getString("rscType");
					if(rscType==null)
					{
						rscType="";
					}
					String rscPublishDate = resultJSON.getString("rscPublishDate");
					if(rscPublishDate==null)
					{
						rscPublishDate="";
					}
					String rscField = resultJSON.getString("rscField");
					if(rscField==null)
					{
						rscField="";
					}
					String rscAuthor = "";
//					JSONObject rscFirstAuthor = resultJSON.getJSONObject("rscFirstAuthor");
//					rscAuthor += rscFirstAuthor.getString("name");
//					JSONArray rscOtherAuthors = resultJSON.getJSONArray("rscOtherAuthors");
//					for (int j = 0; j < rscOtherAuthors.size(); j++) {
//						JSONObject temptemp = JSONObject.fromObject(rscOtherAuthors.get(j));
//						rscAuthor += ", " + temptemp.getString("name");
//					}
					JSONObject listJSON = new JSONObject();
					listJSON.put("rscId", rscId);
					listJSON.put("rscTitle", rscTitle);
					listJSON.put("rscType", rscType);
					listJSON.put("rscPublishDate", rscPublishDate);
					listJSON.put("rscAuthor", rscAuthor);
					listJSON.put("rscField", rscField);
					listJSON.put("visitCount", visitCount);
					rscListJSONArray.add(listJSON);
				} else {    // there are errors if return code does not equal 0
					/* resource information array will be empty */
					log.debug("empty resource info");
					JSONObject listJSON = new JSONObject();
					listJSON.put("rscId", rscId);
					listJSON.put("rscTitle", "");
					listJSON.put("rscType", "");
					listJSON.put("rscPublishDate", "");
					listJSON.put("rscAuthor", "");
					listJSON.put("rscField", "");
					listJSON.put("visitCount", visitCount);
					rscListJSONArray.add(listJSON);
				}
			}
			
			JSONObject rscListJSON = new JSONObject();    // source information list in json by resource count
			rscListJSON.put("retCode", retCode);
			rscListJSON.put("retMsg", retMsg);
			rscListJSON.put("rscList", rscListJSONArray);
			resList = rscListJSON.toString();
		} else {    // hot resource id list is empty or service error
			JSONObject rscListJSON = new JSONObject();    // source information list in json has nothing
			rscListJSON.put("retCode", retCode);
			rscListJSON.put("retMsg", retMsg);
			JSONArray rscListJSONArray = new JSONArray();
			rscListJSON.put("rscList", rscListJSONArray);
			resList = rscListJSON.toString();
		}
		
		//log.debug(resList);
		log.debug("function getHotResByIdList() return");
		
		return resList;
	}
	
	/*
	 * from CDO
	 * according to resource id list and user domain knowledge (e.g. key words)
	 * get resource details list
	 * 在CDO中，根据资源id列表和用户研究领域信息，得到资源元数据列表。
	 */
	public String getHotResByPersonalized (String resIdList, String userDomain, String resCount) {
		JSONObject resIdListJSON = JSONObject.fromObject(resIdList);
		String retCode = resIdListJSON.getString("retCode");
		String retMsg = resIdListJSON.getString("retMsg");
		String resList = "";    // resource information list
		JSONArray keywords = JSONArray.fromObject(userDomain);
		
		/* hot resource id list is not empty if return code equals 3501 */
		if (retCode.equals("3501")) {
			JSONArray rscIdListJSONArray = resIdListJSON.getJSONArray("resultArray");
			int n = rscIdListJSONArray.size();
			
			HashMap<JSONObject, Integer> rscListMap = new HashMap<JSONObject, Integer>();
			
			for (int i = 0; i < n; i++) {
				JSONObject tempJSON = JSONObject.fromObject(rscIdListJSONArray.get(i));
				String rscId = tempJSON.getString("rscId");
				int visitCount = tempJSON.getInt("visitCount");
				
				JSONObject inStr = new JSONObject();      // package the parameters got from front stage
				inStr.put("rscId", rscId);
				JSONObject inJson = new JSONObject();     // package the data to send to back stage
				String methodName = "getRscInfo";         // method name in back stage called by mule
				inJson.put("methodName", methodName);
				inJson.put("jsonStr", inStr);
				String inputStr = inJson.toString();
				
				//log.debug(inStr);
				
				/* get jSon information start */
				String outString = "";                    // get resource information result output by mule
				try {
					MuleClient client = new MuleClient();
					//call WebService
					//UMOMessage umo = client.send("axis:http://localhost:4381/LIBJson/iDlibJson?method=rulesControl", inputStr, null);
					UMOMessage umo = client.send("axis:http://"+localhostUrl+":4381/LIBJson/iDlibJson?method=getRscInfoById", inStr.toString(), null);
					outString = (String)umo.getPayload();
				} catch (Exception e) {axis:http:
					throw new RuntimeException(e);
				}
				/* get jSon information end */
				
				//log.debug(outString);
				
				JSONObject jsonOut = JSONObject.fromObject(outString);
				int code = jsonOut.getInt("retCode");
				
				/* resource information is not empty if return code equals 0 */
				if (code == 0) {
					/* calculate the similarity between user domain and resource */
					JSONObject resultJSON = jsonOut.getJSONObject("result");
					String rscTitle = resultJSON.getString("rscTitle");
					String rscAbstract = resultJSON.getString("rscAbstract");
					String rscSubject = resultJSON.getString("rscSubject");
					int similarity = 0;
					int m = keywords.size();
					for (int j = 0; j < m; j++) {
						JSONObject keyword = JSONObject.fromObject(keywords.get(j));
						String temp = keyword.getString("keyword");
						if (rscTitle.contains(temp)) {
							similarity++;
						}
						if (rscAbstract.contains(temp)) {
							similarity++;
						}
						if (rscSubject.contains(temp)) {
							similarity++;
						}
					}
					
					/* package this resource information */
					String rscType = resultJSON.getString("rscType");
					String rscPublishDate = resultJSON.getString("rscPublishDate");
					String rscField = resultJSON.getString("rscField");
					String rscAuthor = "";
//					JSONObject rscFirstAuthor = resultJSON.getJSONObject("rscFirstAuthor");
//					rscAuthor += rscFirstAuthor.getString("name");
//					JSONArray rscOtherAuthors = resultJSON.getJSONArray("rscOtherAuthors");
//					for (int j = 0; j < rscOtherAuthors.size(); j++) {
//						JSONObject temptemp = JSONObject.fromObject(rscOtherAuthors.get(j));
//						rscAuthor += ", " + temptemp.getString("name");
//					}
					JSONObject listJSON = new JSONObject();
					listJSON.put("rscId", rscId);
					listJSON.put("rscTitle", rscTitle);
					listJSON.put("rscType", rscType);
					listJSON.put("rscPublishDate", rscPublishDate);
					listJSON.put("rscAuthor", rscAuthor);
					listJSON.put("rscField", rscField);
					listJSON.put("visitCount", visitCount);
					
					rscListMap.put(listJSON, similarity);
					
				} else {    // there are errors if return code does not equal 0
					/* resource information array will be empty */
					JSONObject listJSON = new JSONObject();
					listJSON.put("rscId", rscId);
					listJSON.put("rscTitle", "");
					listJSON.put("rscType", "");
					listJSON.put("rscPublishDate", "");
					listJSON.put("rscAuthor", "");
					listJSON.put("rscField", "");
					listJSON.put("visitCount", visitCount);
					
					rscListMap.put(listJSON, -1);
					log.debug(listJSON);
				}
			}
			
			log.debug("begin to sort");
			
			JSONArray rscListJSONArray = new JSONArray();    // resource information array in json
			
			/* sort by similarity */
			List<Map.Entry<JSONObject, Integer>> listData = new ArrayList<Map.Entry<JSONObject, Integer>>(rscListMap.entrySet());
			Collections.sort(listData, new Comparator<Map.Entry<JSONObject, Integer>>() {
				public int compare(Map.Entry<JSONObject, Integer> o1, Map.Entry<JSONObject, Integer> o2) {
					return (int)(o2.getValue() - o1.getValue());
					}
				}
			);
			
			/* add by resource count */
			int k = 1;
			for (Iterator it = listData.iterator(); it.hasNext(); ) {
	 			Map.Entry entry = (Map.Entry) it.next();
	 			//log.debug(entry.getKey() + " : " + entry.getValue());
	 			JSONObject keyJSON = JSONObject.fromObject(entry.getKey());
	 			rscListJSONArray.add(keyJSON);
	 			k++;
	 			if (k > Integer.parseInt(resCount)) {
	 				break;
	 			}
	 		}
			
			JSONObject rscListJSON = new JSONObject();    // source information list in json by resource count
			rscListJSON.put("retCode", retCode);
			rscListJSON.put("retMsg", retMsg);
			rscListJSON.put("rscList", rscListJSONArray);
			resList = rscListJSON.toString();
		} else {    // hot resource id list is empty or service error
			JSONObject rscListJSON = new JSONObject();    // source information list in json has nothing
			rscListJSON.put("retCode", retCode);
			rscListJSON.put("retMsg", retMsg);
			JSONArray rscListJSONArray = new JSONArray();
			rscListJSON.put("rscList", rscListJSONArray);
			resList = rscListJSON.toString();
		}
		
		log.debug("function getHotResByPersonalized() return");
		
		return resList;
	}
	
	/*public String testPersonalized (String resCount) {
		int count = Integer.parseInt(resCount);
		
		String jsonArray = "[{\"keyword\":\"ai\"},{\"keyword\":\"mm\"},{\"keyword\":\"se\"}]";
		JSONArray keywords = JSONArray.fromObject(jsonArray);
		for (int i = 0; i < keywords.size(); i++) {
			JSONObject temp = JSONObject.fromObject(keywords.get(i));
			log.debug(temp.get("keyword"));
		}
		
		jsonArray = "[{\"rscTitle\":\"ai\",\"rscAbstract\":\"se\",\"rscSubject\":\"\",\"rscId\":\"1\",\"rscType\":\"1\",\"rscPublishDate\":\"2008-01-01\",\"rscField\":\"1\"}," +
				"{\"rscTitle\":\"mm\",\"rscAbstract\":\"ai\",\"rscSubject\":\"ai\",\"rscId\":\"2\",\"rscType\":\"2\",\"rscPublishDate\":\"2008-01-01\",\"rscField\":\"1\"}," +
				"{\"rscTitle\":\"se\",\"rscAbstract\":\"\",\"rscSubject\":\"\",\"rscId\":\"3\",\"rscType\":\"3\",\"rscPublishDate\":\"2008-01-01\",\"rscField\":\"1\"}," +
				"{\"rscTitle\":\"cg\",\"rscAbstract\":\"mm\",\"rscSubject\":\"ai\",\"rscId\":\"4\",\"rscType\":\"4\",\"rscPublishDate\":\"2008-01-01\",\"rscField\":\"1\"}," +
				"{\"rscTitle\":\"cv\",\"rscAbstract\":\"mm\",\"rscSubject\":\"ai\",\"rscId\":\"5\",\"rscType\":\"5\",\"rscPublishDate\":\"2008-01-01\",\"rscField\":\"1\"}," +
				"{\"rscTitle\":\"ml\",\"rscAbstract\":\"mm\",\"rscSubject\":\"ai\",\"rscId\":\"6\",\"rscType\":\"6\",\"rscPublishDate\":\"2008-01-01\",\"rscField\":\"1\"}," +
				"{\"rscTitle\":\"dm\",\"rscAbstract\":\"mm\",\"rscSubject\":\"ai\",\"rscId\":\"7\",\"rscType\":\"7\",\"rscPublishDate\":\"2008-01-01\",\"rscField\":\"1\"}," +
				"{\"rscTitle\":\"db\",\"rscAbstract\":\"mm\",\"rscSubject\":\"ai\",\"rscId\":\"8\",\"rscType\":\"8\",\"rscPublishDate\":\"2008-01-01\",\"rscField\":\"1\"}," +
				"{\"rscTitle\":\"ke\",\"rscAbstract\":\"mm\",\"rscSubject\":\"ai\",\"rscId\":\"9\",\"rscType\":\"9\",\"rscPublishDate\":\"2008-01-01\",\"rscField\":\"1\"}," +
				"{\"rscTitle\":\"sw\",\"rscAbstract\":\"mm\",\"rscSubject\":\"ai\",\"rscId\":\"10\",\"rscType\":\"10\",\"rscPublishDate\":\"2008-01-01\",\"rscField\":\"1\"}," +
				"{\"rscTitle\":\"cs\",\"rscAbstract\":\"mm\",\"rscSubject\":\"ai\",\"rscId\":\"11\",\"rscType\":\"11\",\"rscPublishDate\":\"2008-01-01\",\"rscField\":\"1\"}," +
				"{\"rscTitle\":\"ee\",\"rscAbstract\":\"mm\",\"rscSubject\":\"se\",\"rscId\":\"12\",\"rscType\":\"12\",\"rscPublishDate\":\"2008-01-01\",\"rscField\":\"1\"}]";
		
		HashMap<JSONObject, Integer> rscListMap = new HashMap<JSONObject, Integer>();
		
		JSONArray rscInfo = JSONArray.fromObject(jsonArray);
		log.debug(rscInfo.size());
		for (int i = 0; i < rscInfo.size(); i++) {
			JSONObject temp = JSONObject.fromObject(rscInfo.get(i));
			String rscTitle = temp.getString("rscTitle");
			log.debug(rscTitle);
			String rscAbstract = temp.getString("rscAbstract");
			String rscSubject = temp.getString("rscSubject");
			int similarity = 0;
			int m = keywords.size();
			for (int j = 0; j < m; j++) {
				JSONObject keyword = JSONObject.fromObject(keywords.get(j));
				String temptemp = keyword.getString("keyword");
				if (rscTitle.contains(temptemp)) {
					similarity++;
				}
				if (rscAbstract.contains(temptemp)) {
					similarity++;
				}
				if (rscSubject.contains(temptemp)) {
					similarity++;
				}
			}
			log.debug("rscId = " + temp.getString("rscId") + "----" + similarity);
			rscListMap.put(temp, similarity);
		}
		
		List<Map.Entry<JSONObject, Integer>> listData = new ArrayList<Map.Entry<JSONObject, Integer>>(rscListMap.entrySet());
		Collections.sort(listData, new Comparator<Map.Entry<JSONObject, Integer>>() {
			public int compare(Map.Entry<JSONObject, Integer> o1, Map.Entry<JSONObject, Integer> o2) {
				return (int)(o2.getValue() - o1.getValue());
				}
			}
		);
		
		JSONArray rscListJSONArray = new JSONArray();
		int k = 1;
		for (Iterator it = listData.iterator(); it.hasNext(); ) {
 			Map.Entry entry = (Map.Entry) it.next();
 			//log.debug(entry.getKey() + " : " + entry.getValue());
 			JSONObject keyJSON = JSONObject.fromObject(entry.getKey());
 			rscListJSONArray.add(keyJSON);
 			k++;
 			if (k > count) {
 				break;
 			}
 		}
		
		JSONObject rscListJSON = new JSONObject();    // source information list in json has nothing
		rscListJSON.put("retCode", "3501");
		rscListJSON.put("retMsg", "just test");
		rscListJSON.put("rscList", rscListJSONArray);
		String resList = rscListJSON.toString();
		
		log.debug(resList);
		
		return resList;
	}*/
}
